package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.utils.C3p0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    QueryRunner queryRunner = new QueryRunner(C3p0Utils.getDataSource());

    @Override
    public User query(User user) throws SQLException {
        String sql = "select *from user where username =? and password =?;";
        return queryRunner.query(sql, new BeanHandler<>(User.class), user.getUsername(), user.getPassword());
    }

    @Override
    public int addUser(User user) throws SQLException {
        User u = queryUsername(user);
        if (u == null) {
            System.out.println("用户名不存在可以注册!");
            String sql = "insert into user values(null,?,?);";
            return queryRunner.update(sql, user.getUsername(), user.getPassword());
        }
        return 0;
    }

    @Override
    public User queryUsername(User user) throws SQLException {
        String sql = "select *from user where username =?;";
        return queryRunner.query(sql, new BeanHandler<>(User.class), user.getUsername());
    }

    @Override
    public int deleteUser(User user) {
        return 0;
    }

    @Override
    public int updateUser(User user) {
        return 0;
    }


}
